package handler

import (
	"github.com/gin-gonic/gin"
	"zg3zy9/api/request"
	"zg3zy9/inits"
	"zg3zy9/interface/dao"
	"zg3zy9/interface/models"
	"zg3zy9/pkg"
)

func Login(context *gin.Context) {

	var req request.LoginForm
	if err := context.ShouldBind(&req); err != nil {
		context.JSON(500, gin.H{
			"code": "500",
			"msg":  "",
			"data": err.Error(),
		})
		return
	}

	find := dao.Find(req.Mobile)

	if find.Id == 0 {
		context.JSON(200, gin.H{
			"code": "200",
			"msg":  "",
			"data": "账户不存在,自动创建",
		})

	}
	register := models.User{
		Mobile:   req.Mobile,
		Password: req.Password,
	}

	inits.DB.Create(&register)

	token, err := pkg.NewJWT("lx").CreateToken(pkg.CustomClaims{
		ID: find.Id,
	})
	if err != nil {
		return
	}

	context.JSON(200, gin.H{
		"code": "200",
		"msg":  "",
		"data": token,
	})

}
